# -*- encoding: utf-8 -*-

"""
 File 文件存储工具
 
 Author: zsyoung
 
 Date: 2019/01/09 15:00
"""
import csv
import os


def save_text(path, text):
    """
    文本存储

    :param path: 存储路径
    :param text: 文本内容
    :return: None
    """

    __check_path(path)

    with open(path, 'w', encoding='utf-8') as file:
        file.write(text)


def save_file(path, content):
    """
    文件字节流存储

    :param path: 存储路径
    :param content: byte字节流
    :return: None
    """

    __check_path(path)

    with open(path, 'wb') as file:
        file.write(content)


def save_csv(path, header, content):
    """
    文件字节流存储

    :param path: 存储路径
    :param content: byte字节流
    :return: None
    """

    __check_path(path)

    # 1. 创建文件对象
    f = open(path, 'w', encoding='utf-8', newline='')
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    csv_writer.writerow(header)
    # 4. 写入csv文件内容
    for dat in content:
        csv_writer.writerow(dat)
    # 5. 关闭文件
    f.close()

    # with open(path, 'w', encoding='utf-8') as file:
    #     file.write(content)


def read_file(path):
    __check_path(path)
    with open(path, 'r') as f:
        s = f.read()
        return s


def __check_path(path):
    file_name = path.split("/")[-1]
    dir_path = path.replace(file_name, '')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
